package com.qire.manhua.model.viewModel.impl;

import android.view.View;

import com.qire.common.basic.DateUtil;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.base.BaseViewModel;
import com.qire.common.support.base.IViewModel;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerRecyclerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.controller.ComicDirectorySelectorController;
import com.qire.manhua.databinding.LayoutComicDirectorySelectorItemBinding;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.model.entity.ComicBookEntity.ChaptersInfo;
import com.qire.manhua.model.entity.ComicBookEntity.DirectoryInfo;

import java.util.ArrayList;
import java.util.Locale;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.LayoutManager;

public class ComicDirectorySelectorViewModel extends BaseViewModel implements IViewModel {

    private final ArrayList<DirectorySelectorItemViewModel> directoryList = new ArrayList<>();

    private final SummerRecyclerBindAdapter directoryAdapter = new SummerRecyclerBindAdapter(directoryList);
    private final LinearLayoutManager directoryLayoutManager = new LinearLayoutManager(null);

    private ComicBookEntity comicBookEntity;

    private boolean isDescMode = false;

    @Override
    public int getVariableId() {
        return BR.comicDirectorySelectorViewModel;
    }

    //region    #附加管理 begin
    /**
     * 附加属性绑定
     * @param controller 事件控制器
     */
    public void onAddition(ComicDirectorySelectorController controller) {
        this.directoryAdapter.setEventProcess(controller);
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，
     * 页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        this.directoryAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    public void loadComicBookEntity(ComicBookEntity comicBookEntity){
        this.comicBookEntity = comicBookEntity;

        ChaptersInfo readingChapter = comicBookEntity.currentReadingChapters();
        final int readingChapterId = ObjectUtil.isNull(readingChapter) ? -1 : readingChapter.id;

        directoryList.clear();
        for(DirectoryInfo directoryInfo : comicBookEntity.directoryInfoList) {
            if(ObjectUtil.isNull(directoryInfo)) {
                return;
            }
            if(directoryInfo.canNotShow()) {
                return;
            }
            DirectorySelectorItemViewModel itemViewModel = new DirectorySelectorItemViewModel(directoryInfo);
            if(readingChapterId == directoryInfo.chapterId) {
                itemViewModel.isSelected = true;
                directoryLayoutManager.scrollToPositionWithOffset(directoryList.size(), 0);
            }
            directoryList.add(itemViewModel);
        }
        directoryAdapter.notifyDataSetChanged();

        refreshUI();
        set("directoryTitle", comicBookEntity.bookName);
        set("updateTipsText", String.format(Locale.getDefault(), "共%d话", directoryList.size()));

    }

    public ComicBookEntity comicBookEntity() {
        return comicBookEntity;
    }



    //region #UI操作

    public void refreshUI() {
        set("sortModeText", isDescMode ? "倒序" : "正序");
        set("sortModeIconRes", isDescMode ? R.drawable.app_common_icon_sort_down : R.drawable.app_common_icon_sort_up);
    }

    public void toggleSortModeText(){
        isDescMode = !isDescMode;
        refreshUI();
        directoryLayoutManager.setStackFromEnd(isDescMode);
        directoryLayoutManager.setReverseLayout(isDescMode);
    }

    //endregion #UI操作


    //region #UI绑定

    public MutableLiveData<CharSequence> getDirectoryTitle() {
        return get("directoryTitle");
    }

    public MutableLiveData<CharSequence> getUpdateTipsText() {
        return get("updateTipsText");
    }

    public MutableLiveData<CharSequence> getSortModeText() {
        return get("sortModeText");
    }

    public MutableLiveData<Integer> getSortModeIconRes() {
        return get("sortModeIconRes");
    }

    public Adapter getDirectoryAdapter() {
        return directoryAdapter;
    }

    public LayoutManager getDirectoryLayoutManager() {
        return directoryLayoutManager;
    }

    //endregion #UI绑定

    @AdapterEntityBind(viewRid = R.layout.layout_comic_directory_selector_item)
    public class DirectorySelectorItemViewModel extends BaseObservable implements AutoVariable<LayoutComicDirectorySelectorItemBinding> {

        private final DirectoryInfo directoryInfo;
        private boolean isSelected;

        public DirectorySelectorItemViewModel(DirectoryInfo directoryInfo) {
            this.directoryInfo = directoryInfo;
        }

        @Override
        public void bindVariable(LayoutComicDirectorySelectorItemBinding viewBind) {
            viewBind.setDirectorySelectorItemViewModel(this);
        }


        public DirectoryInfo directoryInfo() {
            return directoryInfo;
        }

        @Bindable
        public CharSequence getChapterTitle(){
            return directoryInfo.chapterName;
        }

        @Bindable
        public String getChapterTitleTextColor(){
            return isSelected ? "#ff9204":"#555555";
        }

        @Bindable
        public int getFeeTypeIcon(){
            if(directoryInfo.notNeedBuy())
                return 0;
            if(directoryInfo.isVipFree && UserEntity.self.isVip())
                return R.drawable.app_comic_directory_icon_vip;
            if(directoryInfo.canUnlockedByAd())
                return 0;
            if(directoryInfo.haveLock())
                return R.drawable.app_comic_directory_icon_locked;
            return R.drawable.app_comic_directory_icon_unlocked;
        }

        @Bindable
        public int getAdLockVisible(){
            if(directoryInfo.notNeedBuy())
                return View.GONE;
            if(directoryInfo.isVipFree && UserEntity.self.isVip())
                return View.GONE;
            if(!directoryInfo.haveLock())
                return View.GONE;
            if(!directoryInfo.canUnlockedByAd())
                return View.GONE;

            return View.VISIBLE;
        }

        @Bindable
        public CharSequence getUnlockInfo() {
            String unlockedExpiredTime = directoryInfo.getUnlockedExpiredTime();
            if (directoryInfo.isVipFree && UserEntity.self.isVip())
                return "";
            if(StringUtil.isEmpty(unlockedExpiredTime))
                return "";
            return  "解锁剩余" + DateUtil.yMdHms.toSomeday(unlockedExpiredTime, false).autoFormat(2);
        }

    }

}
